package com.matete.agentmanage.service;

import org.apache.commons.lang3.StringUtils;

import com.aliyuncs.exceptions.ClientException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.matete.agentmanage.common.GlobalSettings;
import com.matete.agentmanage.common.utils.SendMessage;
import com.matete.agentmanage.model.Room;
import com.matete.agentmanage.model.User;

import java.util.List;

import static com.matete.agentmanage.common.GlobalSettings.ROOM_NOTSTATE_VIA;

public class UserService {
	private static final User userDao = new User().dao();
	private static final Room roomDao = new Room().dao();
	private static final SendMessage sendMessage = new SendMessage();

	/**
	 * 获取已通过的申请人列表
	 * 
	 * @param pageNumber
	 *            分页当前页码
	 * @param parentId
	 *            上级代理ID
	 * @param searchContent
	 *            搜索内容
	 * @return
	 */
	public Page<User> getUserRecord(int pageNumber, int parentId, String searchContent) {
		String selectSQL = "SELECT *";
		//String selectSQL = "select a.ID,a.Name,a.Phone,a.QQ,a.Password,a.AgentCount,a.TotalHouseCardCount,a.CurHouseCardCount,a.ParentId,a.State,a.MaxAgentCount,a.AgentCount,a.CreateTime,a.LoginStatus, p.PropertyName AgentLevel ";
		// 如果搜索框里有内容存在
		if (StringUtils.isNotBlank(searchContent)) {
			Page<User> user = null;
			/*room = roomDao.paginate(pageNumber, GlobalSettings.PAGE_SIZE, selectSQL,
					"from agent a , property p where p.PropertyKey =? and a.AgentLevel = p.PropertyValue AND State = ? and a.ID = ?",
					GlobalSettings.PROPERTY_KEY_AGENTLEVEL, GlobalSettings.AGENT_STATE_AUDITING, searchContent);*/
			
			user = userDao.paginate(pageNumber, GlobalSettings.PAGE_SIZE, selectSQL,"from user ,where Status = ?",GlobalSettings.ROOM_STATE_VIA);
			if (user.getList().size() == 0) {
				user = userDao.paginate(pageNumber, GlobalSettings.PAGE_SIZE, selectSQL,
						"from agent a , property p where p.PropertyKey =? and a.AgentLevel = p.PropertyValue AND State = ?  and a.Name like ?",
						GlobalSettings.PROPERTY_KEY_AGENTLEVEL, GlobalSettings.AGENT_STATE_AUDITING,
						"%" + searchContent + "%");
			}
			return user;
		}
		// 如果搜索框没有内容
		return userDao.paginate(pageNumber, GlobalSettings.PAGE_SIZE, selectSQL,"FROM user where Status= ?",GlobalSettings.ROOM_STATE_VIA);
	}
	
	/**
	 * 查询未通过申请列表
	 * 
	 * @param pageNumber
	 *            分页当前页码
	 * @param searchContent
	 *            搜索内容
	 * @return
	 */
	public Page<User> getAgentAuditingList(int pageNumber, String searchContent) {
		//String selectSQL = "select a.ID,a.Name,a.Phone,a.QQ,a.Password,a.AgentCount,a.TotalHouseCardCount,a.CurHouseCardCount,a.ParentId,a.State,a.MaxAgentCount,a.AgentCount,a.CreateTime,a.LoginStatus, p.PropertyName AgentLevel ";
		String selectSQL = "SELECT *";
		if (StringUtils.isNotBlank(searchContent)) {
			Page<User> user = null;
			/*room = roomDao.paginate(pageNumber, GlobalSettings.PAGE_SIZE, selectSQL,
					"from agent a , property p where p.PropertyKey =? and a.AgentLevel = p.PropertyValue AND State = ? and a.ID = ?",
					GlobalSettings.PROPERTY_KEY_AGENTLEVEL, GlobalSettings.AGENT_STATE_AUDITING, searchContent);*/
			user = userDao.paginate(pageNumber, GlobalSettings.PAGE_SIZE, selectSQL,"from user where Status = 0");
			if (user.getList().size() == 0) {
				user = userDao.paginate(pageNumber, GlobalSettings.PAGE_SIZE, selectSQL,
						"from agent a , property p where p.PropertyKey =? and a.AgentLevel = p.PropertyValue AND State = ?  and a.Name like ?",
						GlobalSettings.PROPERTY_KEY_AGENTLEVEL, GlobalSettings.AGENT_STATE_AUDITING,
						"%" + searchContent + "%");
			}
			return user;
		}
		return userDao.paginate(pageNumber, GlobalSettings.PAGE_SIZE, selectSQL,"FROM user where Status = 0");
	}
	/**
	 * 拒绝申请 删除申请数据库
	 * 并发送短信
	 * @param ID
	 */
	public void delUser(String ID) {
		User user = userDao.findById(ID);
		Room room = roomDao.findById(user.getRoomID());
		try {
			sendMessage.SendMSG(user.getPhone(), GlobalSettings.MESSAGE_FAIL_VIA, user.getUserName(), room.getRoomName(), 0);
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String sql = "delete from user where ID = ?";
		Db.update(sql,ID); 
	}

	/**
	 * 删除已经申请人的用户信息
	 * @param id
	 */
	public void deleteUser(String id) {
		String sql = "delete from user where ID = ?";
		Db.update(sql,id);
	}
	
	/**
	 * 审核通过
	 * 将user上申请的时间同步到会议室当中
	 * 同时将短信通知申请人消息
	 * 
	 * @param ID
	 * @throws ClientException 
	 */
	public void userAuditingVia(String ID) throws ClientException {
		User user = userDao.findById(ID);   //time表从此处获得开始时间和结束时间
		user.setStatus(GlobalSettings.AGENT_STATE_VIA).update();
		Room room = roomDao.findById(user.getRoomID());  //time表从此处获得RoomID
		room.setUserName(user.getUserName());
		room.setPhone(user.getPhone());
		room.setDate(user.getDate());
		room.setStartTime(user.getStartTime());
		room.setEndTime(user.getEndTime());
		int Lock = ((int)((Math.random()*9+1)*1000));
        user.setTLock(String.valueOf(Lock));    // 将每个会议室的开锁码保存在申请人中，根据申请人的密码来进行归还操作
		room.setLock(Lock);
        user.update();
		room.update();
		try {
			sendMessage.SendMSG(user.getPhone(), GlobalSettings.MESSAGE_PASS_VIA, user.getUserName(), room.getRoomName(), Lock);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

    /**
     * 根据手机号和解锁码来确定一个人所租借的房间，并将该房间的状态设为0
     */
    public boolean selectUser(String phone, String lock) {
        // 如果找到并成功匹配
        String sql = "SELECT * FROM user WHERE Phone = ? AND t_Lock = ?";
        List<User> users = userDao.find(sql, phone, lock);
        if (!users.isEmpty()) {
            // 如果相互匹配成功，则运行
            User user = users.get(0);
            user.setStatus(ROOM_NOTSTATE_VIA);  // 将会议室调成未使用状态
            user.update();
            return true;
        } else {
            // 如果不能成功匹配，则返回false
            return false;
        }
    }


    /**
     * 根据手机号和解锁码来确定一个人所租借的房间，并将该房间的状态设为0
     */
    public User useUser(String phone, String lock) {
        // 如果找到并成功匹配
        String sql = "SELECT * FROM user WHERE Phone = ? AND t_Lock = ?";
        User user = userDao.findFirst(sql, phone, lock);
        return user;
    }
}
